//
//  QKNewFeatureCollectionViewController.m
//  QKWeibo-OC
//
//  Created by iMac_Kurt on 16/8/24.
//  Copyright © 2016年 Kurt_Qi. All rights reserved.
//

#import "QKNewFeatureCollectionViewController.h"
#import "UIButton+QKButton.h"
#import "Masonry.h"

#pragma mark - QKNewFeatureCell
@interface QKNewFeatureCell : UICollectionViewCell

@property (nonatomic, strong) UIImageView *iconView;

@property (nonatomic, strong) UIButton *startButton;

@property (nonatomic, assign) NSUInteger imageIndex;

@end

@implementation QKNewFeatureCell
// 指定构造方法
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        
        [self setupUI];
        
    }
    
    return self;
}

// 设置界面
- (void)setupUI {
    [self addSubview: self.iconView];
    [self addSubview:self.startButton];
    
}

#pragma mark - 按钮弹出动画
- (void)startButtonAnimation {
    self.startButton.userInteractionEnabled = NO;
    self.startButton.transform = CGAffineTransformMakeScale(0, 0);
    
    [UIView animateWithDuration:1.0
                          delay:0
         usingSpringWithDamping:0.7
          initialSpringVelocity:7
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         self.startButton.transform = CGAffineTransformIdentity;
                     } completion:^(BOOL finished) {
                         self.startButton.userInteractionEnabled = YES;
                     }];
}

// 重写imageIndex的setter
- (void)setImageIndex:(NSUInteger)imageIndex {
    
    _imageIndex = imageIndex;
    
    NSString *imgName = [NSString stringWithFormat:@"new_feature_%lu", (unsigned long)_imageIndex + 1];
    self.iconView.image = [UIImage imageNamed: imgName];

    // 在此处设置按钮隐藏 - 原因：重用时不会显示
    self.startButton.hidden = YES;
    
    //NSLog(@"%lu", (unsigned long)_imageIndex);
    
}

// 布局子控件
- (void)layoutSubviews {
    [self.startButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.mas_centerX);
        make.bottom.equalTo(self.mas_bottom).multipliedBy(0.7);
    }];
}

// 懒加载控件
- (UIImageView *)iconView {
    if (_iconView == nil) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.bounds];
        _iconView = imageView;
    }
    return _iconView;
}
- (UIButton *)startButton {
    if (_startButton == nil) {
        UIButton *button = [UIButton buttonWithTitle:@"开始体验" color:[UIColor whiteColor] backgroundImageName:@"new_feature_finish_button"];
        [button sizeToFit];
        
        _startButton = button;
    }
    return _startButton;
}
@end

#pragma mark - QKNewFeatureCollectionViewController
@interface QKNewFeatureCollectionViewController ()

@property (nonatomic, strong) UIPageControl *pageControl;

@end

@implementation QKNewFeatureCollectionViewController

static NSString * const QKNewFeatureCellId = @"QKNewFeatureCellId";
static NSUInteger QKNewFeatureImageCount = 4;
/// 页码
static NSUInteger pageIndex = 0;

- (instancetype)init {
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    
    if (self = [super initWithCollectionViewLayout:flowLayout]) {
        
        flowLayout.minimumLineSpacing = 0;
        flowLayout.minimumInteritemSpacing = 0;
        flowLayout.itemSize = [UIScreen mainScreen].bounds.size;
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        
        self.collectionView.pagingEnabled = YES;
        self.collectionView.bounces = NO;
        self.collectionView.showsHorizontalScrollIndicator = NO;
        
    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Register cell classes
    [self.collectionView registerClass: [QKNewFeatureCell class] forCellWithReuseIdentifier:QKNewFeatureCellId];
    
    //
    [self setupPageControl];
    
}

#pragma mark - 添加分页指示器
- (void)setupPageControl {
    [self.view addSubview:self.pageControl];
    
    // 布局
    [self.pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.bottom.equalTo(self.view.mas_bottom).multipliedBy(0.95);
    }];
    
}

#pragma mark - 监听滚动
// 实时监听滚动位置（滚动时一直调用）
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    double offsetX = scrollView.contentOffset.x / scrollView.bounds.size.width;
    //NSLog(@"%f", offsetX);
    
    // 通过差值控制页码在0-3之间
    if (offsetX - pageIndex >= 0.5) {
        pageIndex++;
        
    }else if (offsetX - pageIndex <= -0.5) {
        pageIndex--;
    }
    
    //NSLog(@"%d", pageIndex);
    
    self.pageControl.currentPage = pageIndex;
    
}
// 监听停止滚动的时刻（减速运动结束时调用）
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    // 最后一页显示开始按钮
    // 获取当前的cell
    QKNewFeatureCell *cell = (QKNewFeatureCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:pageIndex inSection:0]];
    if (pageIndex == 3) {
        // 显示按钮
        cell.startButton.hidden = NO;
        
        // 执行动画
        [cell startButtonAnimation];
        
        // 添加点击事件
        [cell.startButton addTarget:self action:@selector(didClickStartButton) forControlEvents:UIControlEventTouchUpInside];
    }

}

#pragma mark - 按钮点击事件
- (void)didClickStartButton {
    //NSLog(@"startButtonClicked");
    
    // 切换根控制器
    [[NSNotificationCenter defaultCenter] postNotificationName:QKSwitchRootViewControllerNotification object:nil];
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark <UICollectionViewDataSource>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return QKNewFeatureImageCount;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    QKNewFeatureCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:QKNewFeatureCellId forIndexPath:indexPath];
    
    // Configure the cell
    //cell.backgroundColor = (indexPath.row % 2) == 0 ? [UIColor cyanColor] : [UIColor orangeColor];
    
    cell.imageIndex = indexPath.row;
    
    return cell;
}

#pragma mark - 懒加载控件
- (UIPageControl *)pageControl {
    if (_pageControl == nil) {
        UIPageControl *pageControl = [[UIPageControl alloc] init];
        
        pageControl.numberOfPages = QKNewFeatureImageCount;
        pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
        pageControl.currentPageIndicatorTintColor = [UIColor orangeColor];
        
        _pageControl = pageControl;
    }
    return _pageControl;
}

@end


